from django.contrib.auth.models import Group, User
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework import generics, mixins, permissions, serializers, viewsets
from rest_framework.authentication import (BaseAuthentication,
                                           SessionAuthentication)
from rest_framework.decorators import (action, api_view, permission_classes,
                                       throttle_classes)
from rest_framework.exceptions import ValidationError
from rest_framework.parsers import JSONParser
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.throttling import UserRateThrottle
from rest_framework.views import APIView

from drf.models import Demo
from drf.serializers import (Demo1Serializer, DemoSerializer, GroupSerializer,
                             UserSerializer)


# 关闭drf 中的 csrf 验证
class CsrfExemptSessionAuthentication(SessionAuthentication):

    def enforce_csrf(self, request):
        return  # To not perform the csrf check previously happening


#  限流处理
class OncePerDayUserThrottle(UserRateThrottle):
    rate = '10/min'


@api_view(['GET', 'POST'])
@throttle_classes([OncePerDayUserThrottle])
# @authentication_classes([CsrfExemptSessionAuthentication, BaseAuthentication])  # 取消drf 的csrf 验证
@permission_classes([
    IsAuthenticated])  # AllowAny(所有用户访问) IsAuthenticated（登录用户 访问） IsAdminUser（超级管理员访问） IsAuthenticatedOrReadOnly （功能权限访问）
def view(request):
    print("----------", repr(UserSerializer()))
    print("获取get 内容", request.query_params)
    print("获取post 内容", request.data)

    if request.method == 'POST':
        return Response({"message": "post1"})
    return Response({"message": "get2"})


class LisUsers(APIView):
    """
        APIView 使用案例
    """
    authentication_classes = (CsrfExemptSessionAuthentication, BaseAuthentication)

    def get(self, request,format='json'):
        usernames = [user.username for user in User.objects.all()]
        return Response(['get'])

    def post(self, request):
        usernames = [user.username for user in User.objects.all()]
        return Response(['post'])

    @csrf_exempt  # 免除csrf验证
    def dispatch(self, request, *args, **kwargs):
        return super(LisUsers, self).dispatch(request, *args, **kwargs)


class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer
    permission_classes = [permissions.IsAuthenticated]


class GroupViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    容器启动时 运行
    """
    print('GroupViewSet=============================1')
    queryset = Group.objects.all()
    serializer_class = GroupSerializer
    permission_classes = [permissions.IsAuthenticated]

    # 自定义方法
    @action(detail=False)
    def my_method1(self,request,*args,**kwargs):
        return JsonResponse({'msg':'自定义方法'})

from rest_framework.permissions import BasePermission


# 自定义权限
class MyPermission(BasePermission):

    def has_permission(self, request, view):
        if request.query_params.get('user') == 'admin':
            return True
        else:
            return False

# 新增和列表            
@csrf_exempt
def demo_list(request):
    if(request.method=='GET'):
        demos=Demo.objects.all()
        return JsonResponse(Demo1Serializer(demos,many=True).data,safe=False)
    elif(request.method=='POST'):
        data=request.POST
        serializer=Demo1Serializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data,status=201)
        error=list(serializer.errors.values())
        print('error:',error)    
        return JsonResponse({'error':error[0][0]},status=400)

# 修改/查看/删除
@csrf_exempt
def demo_view(request,pk):
    try:
      demo=Demo.objects.get(pk=pk)
    except Demo.DoesNotExist:
      return JsonResponse({'error':'demo 不存在'},status=400)
    if(request.method=='GET'):
        return JsonResponse(Demo1Serializer(demo).data,safe=False)
    elif(request.method=='POST'):
        serilize=Demo1Serializer(demo,data=request.POST)
        if serilize.is_valid():
            serilize.save()
            return JsonResponse(serilize.data)
        error=list(serilize.errors.values())
        print('error:',error)    
        return JsonResponse({'error':error[0][0]},status=400)   
    elif request.method=='DELETE':
        demo.delete()
        return JsonResponse({'msg':'success'})

# demo_list的第一次重构
@csrf_exempt
@api_view(['GET', 'POST'])
def demo_list1(request):
    data = request.data
    serilizer = DemoSerializer(data=data)
    try:
        serilizer.is_valid(raise_exception=True)
    except ValidationError as e:
        print(serilizer.errors)
        print(serilizer.fields.values())
    # print(serilizer.errors)
    # print(serilizer.error_messages)
    # print(serilizer.data)
    # print(serilizer.validated_data)
    return Response(serilizer.data)

# demo_list第二次重构
class DemoList2(mixins.ListModelMixin,
                    mixins.CreateModelMixin,
                    generics.GenericAPIView):
    queryset = Demo.objects.all()
    serializer_class = Demo1Serializer

    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)
